package com.talkyun.openx.server.core;

import com.talkyun.openx.server.helper.MatchHelper;

import java.util.List;

public abstract class AbstractInterceptor implements Interceptor {
    public String FLAG_SR = "$SR";
    public String FLAG_SP = "$SP";

    private List<String> patterns;
    private List<String> whitePatterns;

    public void setMatchPattern(List<String> patterns) {
        this.patterns = patterns;
    }

    public void setNotMatchPattern(List<String> patterns) {
        whitePatterns = patterns;
    }

    @Override
    public void onMessageIn(ServiceContext ctx, ServiceRequest sr) throws Throwable {
        ctx.putIfNull(FLAG_SR, sr);

        if (this.isMatched(ctx)) {
            this.doMessageIn(sr);
        }
    }

    @Override
    public void onMessageOut(ServiceContext ctx, ServiceResponse sp) throws Throwable {
        ctx.putIfNull(FLAG_SP, sp);

        if (this.isMatched(ctx)) {
            doMessageOut(sp);
        }
    }

    @Override
    public void onException(ServiceContext ctx, Throwable t) throws Throwable {
        if (this.isMatched(ctx)) {
            doException(t);
        }
    }

    protected boolean isMatched(ServiceContext ctx) {
        ServiceRequest sr = (ServiceRequest) ctx.getValue(FLAG_SR);
        String mapping = sr.getMapping();
        String method = sr.getMethod();

        // ignore white pattern first
        if (whitePatterns != null && !whitePatterns.isEmpty()) {
            for (String pattern : whitePatterns) {
                if (this.isBlank(pattern)) {
                    continue;
                }
                if (MatchHelper.isMatched(pattern.trim(), mapping, method)) {
                    return false;
                }
            }
        }

        // match pattern
        if (patterns == null) {
            return false;
        }
        for (String pattern : patterns) {
            if (this.isBlank(pattern)) {
                continue;
            }
            if (MatchHelper.isMatched(pattern.trim(), mapping, method)) {
                return true;
            }
        }
        return false;
    }

    protected boolean isBlank(String s) {
        return s == null || s.trim().length() == 0;
    }

    protected void doMessageIn(ServiceRequest sr) throws Throwable {
        // impl by sub-class
    }

    protected void doMessageOut(ServiceResponse sp) throws Throwable {
        // impl by sub-class
    }

    protected void doException(Throwable t) throws Throwable {
        // impl by sub-class
    }
}
